package top.seefly.cloudstream.demos;

import ch.qos.logback.core.testUtil.RandomUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;

import java.util.Random;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * 1 开启路由功能
 *  spring.cloud.stream.function.routing.enabled=true
 * 2 路由表达式，返回值是消费者的name
 *  spring.cloud.function.routing-expression="T(java.lang.System).currentTimeMillis() % 2 == 0 ? 'routeAppend' : 'odd'"
 * 3 配置内置的路由binding
 *  spring.cloud.stream.bindings.functionRouter-in-0.destination,配置路由监听的topic
 *  spring.cloud.stream.bindings.functionRouter-out-0.destination,配置路由转发到的Function函数，输出
 *
 *
 *
 *
 * @author liujianxin
 * @date 2023/07/30 17:11
 */
@Configuration
public class RoutingDemo {
    static String[] arr = new String[]{"even","odd","routeAppend","destinationAsPayload"};
    public static String getFunctionName() {
        return arr[RandomUtil.getPositiveInt() % arr.length];
    }


    @Bean
    public Consumer<String> even() {
        return value -> System.out.println("EVEN: " + value);
    }

    @Bean
    public Consumer<String> odd() {
        return value -> System.out.println("ODD: " + value);
    }

    @Bean
    public Function<String,String> routeAppend() {
        return data -> {
            String a = data+"  routeAppend";
            System.out.println(a);
            return a;
        };
    }


    @Bean
    public Function<String, Message<String>> destinationAsPayload() {
        return value -> {
            String ss = value +"  destinationAsPayload";
            return MessageBuilder.withPayload(ss)
                    .setHeader("spring.cloud.stream.sendto.destination", "route-in-0").build();};
    }
}
